package com.msb.juc.c_026;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class T11_FixedThreadPool {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 1-20万里面有多少个质数
        long start = System.currentTimeMillis();
        List<Integer> prime = getPrime(1, 200_000);
        long end = System.currentTimeMillis();
        System.out.println(end - start);

        // ----------------------------------------------

        // 定义4核CPU，创建4个线程的线程池
        final int cpuCoreNum = 4;
        ExecutorService service = Executors.newFixedThreadPool(cpuCoreNum);

        // 4个任务并行执行
        MyTask t1 = new MyTask(1, 80000);
        MyTask t2 = new MyTask(80001, 130000);
        MyTask t3 = new MyTask(130001, 170000);
        MyTask t4 = new MyTask(170001, 200000);

        start = System.currentTimeMillis();

        // 任务异步提交
        Future<List<Integer>> f1 = service.submit(t1);
        Future<List<Integer>> f2 = service.submit(t2);
        Future<List<Integer>> f3 = service.submit(t3);
        Future<List<Integer>> f4 = service.submit(t4);

        // 获取任务执行结果
        f1.get();
        f2.get();
        f3.get();
        f4.get();
        end = System.currentTimeMillis();
        System.out.println(end - start);

    }

    static class MyTask implements Callable<List<Integer>> {

        int startPos, endPos;

        public MyTask(int startPos, int endPos) {
            this.startPos = startPos;
            this.endPos = endPos;
        }

        @Override
        public List<Integer> call() throws Exception {
            List<Integer> r = getPrime(startPos, endPos);
            return r;
        }
    }

    static boolean isPrime(int num) {
        for (int i = 2; i <= num / 2; i++) {
            if (num % i == 0) {
                return false;
            }
        }

        return true;
    }

    static List<Integer> getPrime(int start, int end) {
        List<Integer> results = new ArrayList<>();
        for (int i = start; i < end; i++) {
            if (isPrime(i)) {
                results.add(i);
            }
        }
        return results;
    }
}
